package com.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by ke on 2015/10/10.
 */
public class DateUtil {
    public static final String FORMAT_NORMAL = "yyyy-MM-dd HH:mm:ss";
    public static final String FORMAT_YEAR_DAY = "yyyy-MM-dd";
    public static final String FORMAT_NORMAL_T = "yyyy-MM-dd'T'HH:mm:ss";

    /**
     * n天后的日期
     */
    public static Date addDays(Date date, int amount) {
        return add(date, Calendar.DAY_OF_MONTH, amount);
    }

    /**
     * n小时后的日期
     */
    public static Date addHours(Date date, int amount) {
        return add(date, Calendar.HOUR_OF_DAY, amount);
    }

    /**
     * n分钟后的日期
     */
    public static Date addMinutes(Date date, int amount) {
        return add(date, Calendar.MINUTE, amount);
    }

    /**
     * n秒后的日期
     */
    public static Date addSeconds(Date date, int amount) {
        return add(date, Calendar.SECOND, amount);
    }

    public static Date add(Date date, int calendarField, int amount) {
        if (date == null) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }

    /**
     * 以"yyyy-MM-dd HH:mm:ss"为格式，将字符串转化成日期
     */
    public static Date toDate(String dateStr) {
        return toDate(dateStr, FORMAT_NORMAL);
    }

    /**
     *  将字符串转换成日期
     */
    public static Date toDate(String dateStr, String pattern) {
        if (null == dateStr || dateStr.length() == 0) {
            return null;
        }
        if (null == pattern || pattern.length() == 0) {
            return null;
        }
        Date result = null;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            result = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  以"yyyy-MM-dd HH:mm:ss"为格式，将日期转换成字符串
     */
    public static String toString(Date date) {
        return toString(date, FORMAT_NORMAL);
    }

    /**
     *  将日期转换成字符串
     */
    public static String toString(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(DateUtil.toString(date));
        System.out.println(DateUtil.toString(date, DateUtil.FORMAT_NORMAL));
        System.out.println(DateUtil.toString(date, DateUtil.FORMAT_NORMAL_T));
        System.out.println(DateUtil.toString(date, DateUtil.FORMAT_YEAR_DAY));
        String aa = "2015-04-03T11:11:11";
        Date date2 = DateUtil.toDate(aa, DateUtil.FORMAT_NORMAL_T);
        System.out.println(DateUtil.toString(date2));
    }
}
